package com.ayf.payment.game.api.controller;

import com.ayf.payment.game.api.dto.criteria.OrderInfoCriteria;
import com.ayf.payment.game.api.service.MerchantBalanceRecordService;
import com.ayf.payment.game.api.service.MerchantPayOrderService;
import com.ayf.payment.game.api.service.OrderService;
import com.ayf.payment.game.api.service.platform.MerchantCashOutService;
import com.ayf.payment.game.api.service.platform.MerchantSettleService;
import com.ayf.payment.game.api.utils.DateUtils;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @Description: 定时任务手动执行
 * @Author: zh-liang
 * @Date : 2020-05-27 17:52
 */
@RestController
@RequestMapping("/t")
public class TaskController {

    @Autowired
    private MerchantBalanceRecordService merchantBalanceRecordService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private MerchantCashOutService merchantCashOutService;

    @Autowired
    private MerchantPayOrderService merchantPayOrderService;

    @Autowired
    private MerchantSettleService merchantSettleService;

    @PostMapping("/balancePaymentsAdd")
    public String balancePaymentsAdd(@RequestParam("key") String key) {
        if (StringUtils.isBlank(key) || !"bug0527".equals(key)) {
            return "key错误";
        }
        String traceId = SnowFlakeUtils.getUniqueId();

        OrderInfoCriteria orderCriteria = new OrderInfoCriteria();
        Date dayBeforeDay = DateUtils.getDayBeforeDay(1);
        String yesterday = DateUtils.dateToString(dayBeforeDay, DateUtils.formatPattern);
        orderCriteria.setStartTime(yesterday + " 00:00:00");
        orderCriteria.setEndTime(yesterday + " 23:59:59");
        orderCriteria.setDate(DateUtils.dateToInteger(dayBeforeDay));
        Set<Integer> idSet = new HashSet<Integer>();
        //商户收入
        Map<Integer, Map<String, Object>> tradeMap = orderService.selectSumAmount(orderCriteria);
        Set<Integer> tradeSet = tradeMap.keySet();
        idSet.addAll(tradeSet);
        //代理商收入
        Map<Integer, Map<String, Object>> proxyMap = orderService.selectSumProxyIncome(orderCriteria);
        Set<Integer> proxySet = proxyMap.keySet();
        idSet.addAll(proxySet);
        //商户结算
        Map<Integer, Map<String, Object>> settleMap = merchantSettleService.selectSumSettle(orderCriteria);
        Set<Integer> settleSet = settleMap.keySet();
        idSet.addAll(settleSet);
        //提现
        Map<Integer, Map<String, Object>> withdrawalMap = merchantCashOutService.selectSumWithdrawal(orderCriteria);
        Set<Integer> withdrawal = withdrawalMap.keySet();
        idSet.addAll(withdrawal);
        //代付
        Map<Integer, Map<String, Object>> payMap = merchantPayOrderService.selectSumPay(orderCriteria);
        Set<Integer> paySet = payMap.keySet();
        idSet.addAll(paySet);

        List<Integer> idsList = new ArrayList<>(idSet);
        int size = 200;
        int num = idsList.size() % size == 0 ? idsList.size() / size : idsList.size() / size + 1;

        LogPortal.info("[{}][{}]收支记录批量插入开始执行，执行的总次数为[{}]，每次执行处理的的最大商户数量为[{}]", traceId, yesterday,
                num, size);

        for (int i = 0; i < num; i++) {
            int count = i;
            List<Integer> subList = idsList.subList(i * size, i == num - 1 ? idsList.size() : (i + 1) * size);
            LogPortal.info("[{}]开始执行第[{}]次收支记录批量插入，本次处理的商户数量为[{}]", traceId, i + 1, subList.size());
            try {
                merchantBalanceRecordService.addBudgets(subList, tradeMap, proxyMap, settleMap, withdrawalMap, payMap);
                LogPortal.info("[{}]第[{}/{}]次收支记录批量插入成功，本次处理的商户数量为[{}]:{}", traceId, count + 1, num,
                        subList.size(), subList);
            } catch (Exception e) {
                LogPortal.error("[{}]第[{}/{}]次收支记录批量插入失败，发生了[{}]异常，错误描述[{}]，本次处理的商户数量为[{}]:{}", traceId,
                        count + 1, num, e.getClass().getName(), e.getMessage(), subList.size(), subList);
            } finally {

            }
        }
        return "手动执行收支记录汇总成功";
    }

    @PostMapping("/merchantSettleRetry")
    public String merchantSettleRetry(@RequestParam("settleDate") String settleDate) {
        try {
            merchantSettleService.merchantSettleCreate(settleDate);
        } catch (Exception e) {
            String traceId = SnowFlakeUtils.getTraceId();
            LogPortal.error("{} 手动执行结算单失败 发生{}异常",e,traceId,e.getClass().getName());
            return "执行失败，错误码:"+traceId;
        }
        return "执行成功";
    }

}